package com.summer.applet;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

import com.summer.applet.entity.Flower;
import com.summer.applet.entity.GameDirector;
import com.summer.applet.entity.GameDirector.CollisionDetection;
import com.summer.applet.entity.GameDirector.Node;
import com.summer.applet.entity.GameDirector.PlayScene;
import com.summer.applet.entity.Rocker;
import com.summer.applet.entity.Snake;

public class SnakeGame extends Applet implements PlayScene,CollisionDetection{

	/** */
	private static final long serialVersionUID = 1L;
	
	protected Snake snake = new Snake();
	protected ArrayList<Flower> flowerList = new ArrayList<Flower>();
	protected GameRule gameRule = new GameRule();
	
	@Override
	public void init() {
		setSize(720, 512);
		addKeyListener(keyListener);
		GameDirector.gameDirector.addCollisionDetection(this);
		GameDirector.gameDirector.addPlayScene(this);
		GameDirector.gameDirector.start();
		flowerList.add(Flower.create(getWidth(), getHeight()));	
		super.init();
	}
	
	@Override
	public void paint(Graphics graphics) {
//		super.paint(graphics);
		
		snake.draw(graphics);
		for(Flower flower : flowerList) {
			flower.draw(graphics);
		}
	}
	
	private KeyListener keyListener = new KeyListener(){

		@Override
		public void keyTyped(KeyEvent e) { }

		@Override
		public void keyPressed(KeyEvent e) {
			Rocker.control(e, snake);
		}

		@Override
		public void keyReleased(KeyEvent e) { }
		
	};


	@Override
	public void updateScene() {
		repaint();
		snake.runAction();
	}
	 
	@Override
	public boolean detection(GameDirector gameDirector) {
		if(snake.lifeState()) {
//			gameRule.aiEat(snake);
			if(gameRule.outOfRange(snake)){
				snake.setLifeState(false);
			}
			
			for(Flower flower : flowerList) {
				snake.eatAction(flower);
			}
		}else{
			gameDirector.stop();
		}
		return false;
	}
	
	public class GameRule {

		public boolean outOfRange(Snake snake) {
			Rectangle range = new Rectangle(0,0,getWidth(),getHeight());
			if(!range.contains(snake.getLocation().x, snake.getLocation().y)) {
				return true;
			}
			return false;
		}
		
		private void aiEat(Snake snake) {
			if(flowerList.isEmpty()) return;
			Flower flower = flowerList.get(0);
			Point fPoint = flower.getLocation();
			Point sPoint = snake.getLocation();
			if(fPoint.x != sPoint.x) {
				int direction = sPoint.x - fPoint.x;
				if(direction>0) {
					snake.directionAction(Snake.DIRECTION_LEFT);
				}else {
					snake.directionAction(Snake.DIRECTION_RIGHT);
				}
			}
			if(fPoint.y != sPoint.y){
				int direction = sPoint.y - fPoint.y;
				if(direction>0) {
					snake.directionAction(Snake.DIRECTION_UP);
				}else {
					snake.directionAction(Snake.DIRECTION_DOWN);
				}
			}
		} 
		
	}

	@Override
	public void addNode(Node node) {
		// TODO Auto-generated method stub
		
	}
	
}
